package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.dao.*;
import io.renren.entity.*;
import io.renren.entity.VO.PersonDispatchEntityVO;
import io.renren.utils.DateUtils;
import io.renren.utils.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import io.renren.service.SbydglService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;


@Transactional(propagation= Propagation.REQUIRED)
@Service("sbydglService")
public class SbydglServiceImpl implements SbydglService {
	@Autowired
	private SbydglDao sbydglDao;
	@Autowired
	private SbydglDetDao sbydglDetDao;
	@Autowired
	private SbjsglDao sbjsglDao;
	@Autowired
	private BusinesspayDao businesspayDao;
	@Override
	public SbydglEntity queryObject(Integer ydId){
		return sbydglDao.queryObject(ydId);
	}
	
	@Override
	public List<SbydglEntity> queryList(Map<String, Object> map){
		return sbydglDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return sbydglDao.queryTotal(map);
	}
	
	@Override
	public void save(SbydglEntity sbydgl){
		sbydglDao.save(sbydgl);
	}

	@Override
	public void update(SbydglEntity sbydgl){
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ydId", sbydgl.getYdId().toString());
			map.put("startDate", sbydgl.getStartDate());
			map.put("endDate", sbydgl.getEndDate());
			sbydglDetDao.updateStartDate(map);//修改第一批明细生效日期
			sbydglDetDao.updateEndDate(map);//修改所有的失效日期
			List<SbydglDetEntity> sbydglDetEntitylist = sbydglDetDao.queryListByYdId(map);
			for (SbydglDetEntity sbydglDetEntity : sbydglDetEntitylist) {
				if (sbydglDetEntity.getStartDate() != null && sbydglDetEntity.getEndDate() != null) {
					int months = DateUtils.joinMonthsContain(sbydglDetEntity.getStartDate(), sbydglDetEntity.getEndDate());
					double moeny = sbydgl.getBxje();
					map.put("sjjfje", getSjjfje(months, moeny));
					map.put("yddetId",sbydglDetEntity.getYddetId() );
					sbydglDetDao.updateSjjfje(map);//通过生效日期和失效日期来算出对应的实际交付金额
				}
			}
			sbydglDao.update(sbydgl);
		}catch (RRException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void delete(Integer ydId){
		sbydglDao.delete(ydId);
	}
	
	@Override
	public void deleteBatch(Integer[] ydIds){
		sbydglDao.deleteBatch(ydIds);
	}

	@Override
	public void addSbyd(JSONObject params ,SysUserEntity sysUserEntity) {
		try{
			String[] ids = params.getString("ids").split(",");
			String sbjsglId = "";
			SbjsglEntity sbjsglEntity = new SbjsglEntity();
			if(params.get("sbjsglId")!=null){
				 sbjsglId = params.get("sbjsglId").toString();
				 sbjsglEntity = sbjsglDao.queryObject(sbjsglId);
					if(sbjsglEntity==null){
						throw new RRException("未找到对应的商保类型！");
					}
			}else{
				throw new RRException("请选择商保类型！");
			}
			String sblx = sbjsglEntity.getSblx();
			String bxgs = sbjsglEntity.getBxgs();
			Double bxje = sbjsglEntity.getBxje();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sblx",sblx);
			map.put("bxgs",bxgs);
			map.put("bxje",bxje);
			List<SbydglEntity>  SbydglEntitylist =sbydglDao.queryListByType(map);
			SbydglEntity sbydgl = new SbydglEntity();
			if(SbydglEntitylist==null||SbydglEntitylist.size()==0){
				sbydgl.setSblx(sblx);
				sbydgl.setBxgs(bxgs);
				sbydgl.setBxje(Double.valueOf(bxje));
				sbydglDao.save(sbydgl);
			}else if(SbydglEntitylist.size()==1){
				 sbydgl = SbydglEntitylist.get(0);
			}else if(SbydglEntitylist.size()>1){
				throw new RRException("您要参保的类型有多条有效记录请重新选择参保类型！");
			}
			for(String id :ids){
				PersonDispatchEntityVO personDispatchEntityVO =  sbydglDao.queryPersonDispatchEntityVO(id);
				if(personDispatchEntityVO!=null){
					SbydglDetEntity sbydglDetEntity = new SbydglDetEntity();
					sbydglDetEntity.setYdId(sbydgl.getYdId());
					sbydglDetEntity.setUserId(Integer.parseInt(personDispatchEntityVO.getPersonId()));
					sbydglDetEntity.setIdNo(personDispatchEntityVO.getIdno());
					sbydglDetEntity.setUserName(personDispatchEntityVO.getName());
					sbydglDetEntity.setSex(personDispatchEntityVO.getSex());
					sbydglDetEntity.setAge(personDispatchEntityVO.getAge());
					sbydglDetEntity.setSettlementId(personDispatchEntityVO.getSettlementId());
					sbydglDetEntity.setSettlementName(personDispatchEntityVO.getSettlementname());
					sbydglDetEntity.setInputperson(sysUserEntity.getUsername());
					sbydglDetEntity.setEntrytime(new Date());
					sbydglDetEntity.setEnabled("0");
					sbydglDetEntity.setPaystatus("0");
					sbydglDetEntity.setInstastatus("0");
					if(sbydgl.getStartDate()!=null&&sbydgl.getEndDate()!=null){
						//判断是否有生效时间跟失效时间
						GregorianCalendar ca = new GregorianCalendar();
						//SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
						Calendar c = Calendar.getInstance();
						 	if(ca.get(GregorianCalendar.AM_PM)==0){//判断是上午还是下午如果是上午加1天，是下午加2天
								c.add(Calendar.DAY_OF_MONTH, 1);
							}else{
								c.add(Calendar.DAY_OF_MONTH, 2);
							}
						sbydglDetEntity.setStartDate(c.getTime());
						sbydglDetEntity.setEndDate(sbydgl.getEndDate());
							int months = DateUtils.joinMonthsContain(sbydglDetEntity.getStartDate(),sbydglDetEntity.getEndDate());
							double moeny = sbydgl.getBxje();
						sbydglDetEntity.setSjjfje(getSjjfje(months,moeny));
						sbydglDetEntity.setBatchCode("2");
					}else{
						sbydglDetEntity.setBatchCode("1");
					}
					sbydglDetDao.save(sbydglDetEntity);
				}else{
					throw new RRException("某条数据未找到！");
				}
			}
		}catch (RRException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static double getSjjfje(int months,double money){
		double sjmoney=0;
		if(months==12){
			sjmoney = money*(1-0);
		}else if(months==11){
			sjmoney = money*(1-0.05);
		}else if(months==10){
			sjmoney = money*(1-0.1);
		}else if(months==9){
			sjmoney = money*(1-0.15);
		}else if(months==8){
			sjmoney = money*(1-0.2);
		}else if(months==7){
			sjmoney = money*(1-0.3);
		}else if(months==6){
			sjmoney = money*(1-0.4);
		}else if(months==5){
			sjmoney = money*(1-0.5);
		}else if(months==4){
			sjmoney = money*(1-0.6);
		}else if(months==3){
			sjmoney = money*(1-0.7);
		}else if(months==2){
			sjmoney = money*(1-0.8);
		}else if(months==1){
			sjmoney = money*(1-0.9);
		}
		return sjmoney;
	}
	@Override
	public List<String> getBatchCode() {
		return 	sbydglDao.getBatchCode();
	}

	@Override
	public void addBusinesspay(Integer[] ydDetIds, HttpServletRequest request,SysUserEntity sysUserEntity) {
		try {
			String batchcode = "";
			String ydid = request.getParameter("ydid");
			SbydglEntity sbydglEntity = sbydglDao.queryObject(ydid);
			if ("".equals(request.getParameter("batchcode")) && request.getParameter("batchcode") != null) {//如果batchcode为空就是新增批次号
				batchcode = DateUtils.format(new Date(), "yyyyMMdd");
			} else {
				batchcode = request.getParameter("batchcode");
			}
			for (int ydDetId : ydDetIds) {
				SbydglDetEntity sbydglDetEntity = sbydglDetDao.queryObject(ydDetId);
				if("1".equals(sbydglDetEntity.getPaystatus())){
					throw new RRException("勾选的数据中有付款中的数据！");
				}
				BusinesspayEntity businesspayEntity = new BusinesspayEntity();
				businesspayEntity.setBatchcode(batchcode);
				businesspayEntity.setYddetid(sbydglDetEntity.getYddetId().toString());//从表信息id
				businesspayEntity.setSettlementid(sbydglDetEntity.getSettlementId());//从表信息
				businesspayEntity.setSettlementname(sbydglDetEntity.getSettlementName());//从表信息
				businesspayEntity.setName(sbydglDetEntity.getUserName());//从表信息
				businesspayEntity.setIdnumber(sbydglDetEntity.getIdNo());//从表信息
				businesspayEntity.setChsex(sbydglDetEntity.getSex());//从表信息
				businesspayEntity.setAge(sbydglDetEntity.getAge());//从表信息
				businesspayEntity.setInsurancetype(sbydglEntity.getSblx());//主表信息
				businesspayEntity.setInsuranceamount(sbydglDetEntity.getSjjfje());//保险金额
				businesspayEntity.setInsuranceid(sbydglEntity.getBxCode());//主表信息
				businesspayEntity.setInputperson(sysUserEntity.getUsername());
				businesspayEntity.setInputdate(new Date());
				businesspayEntity.setPay("1");
				businesspayEntity.setAudit("0");
				businesspayDao.save(businesspayEntity);
				Map<String, Object> map = new HashMap<String, Object>();
				//修改原表状态改成付款中
				map.put("ydDetId", ydDetId);
				map.put("paystatus", "1");
				sbydglDetDao.updatePayStatus(map);
			}

		}catch (RRException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
